<template>
  <view class="requests-container">
    <!-- 请求统计 -->
    <view class="stats-section">
      <view class="stat-item">
        <text class="stat-number">{{ pendingCount }}</text>
        <text class="stat-label">待处理</text>
      </view>
      <view class="stat-item">
        <text class="stat-number">{{ receivedCount }}</text>
        <text class="stat-label">收到请求</text>
      </view>
      <view class="stat-item">
        <text class="stat-number">{{ sentCount }}</text>
        <text class="stat-label">已发送</text>
      </view>
    </view>
    
    <!-- 请求分类 -->
    <view class="category-tabs">
      <view 
        v-for="category in categories" 
        :key="category.id"
        class="category-tab"
        :class="{ active: activeCategory === category.id }"
        @click="switchCategory(category.id)"
      >
        <text class="tab-text">{{ category.name }}</text>
        <view v-if="category.count > 0" class="tab-badge">{{ category.count }}</view>
      </view>
    </view>
    
    <!-- 收到的请求 -->
    <view v-if="activeCategory === 'received'" class="requests-list">
      <view class="section-title">
        <text class="title-text">收到的请求</text>
        <text class="title-count">({{ receivedRequests.length }})</text>
      </view>
      
      <view v-if="receivedRequests.length === 0" class="empty-state">
        <text class="empty-icon">📨</text>
        <text class="empty-text">暂无好友请求</text>
      </view>
      
      <view v-else class="request-list">
        <view 
          v-for="request in receivedRequests" 
          :key="request.id"
          class="request-item"
        >
          <view class="user-avatar-section">
            <image 
              v-if="request.fromUser.avatar" 
              :src="request.fromUser.avatar" 
              class="user-avatar"
              mode="aspectFill"
            />
            <view v-else class="default-avatar">
              <text class="avatar-text">{{ request.fromUser.name.charAt(0) }}</text>
            </view>
          </view>
          
          <view class="request-info">
            <text class="user-name">{{ request.fromUser.name }}</text>
            <text class="request-message">{{ request.message || '我想加你为好友' }}</text>
            <text class="request-time">{{ formatTime(request.createTime) }}</text>
          </view>
          
          <view class="request-actions">
            <button class="accept-btn" @click="acceptRequest(request)">
              同意
            </button>
            <button class="reject-btn" @click="rejectRequest(request)">
              拒绝
            </button>
          </view>
        </view>
      </view>
    </view>
    
    <!-- 已发送的请求 -->
    <view v-if="activeCategory === 'sent'" class="requests-list">
      <view class="section-title">
        <text class="title-text">已发送的请求</text>
        <text class="title-count">({{ sentRequests.length }})</text>
      </view>
      
      <view v-if="sentRequests.length === 0" class="empty-state">
        <text class="empty-icon">📤</text>
        <text class="empty-text">暂无已发送的请求</text>
      </view>
      
      <view v-else class="request-list">
        <view 
          v-for="request in sentRequests" 
          :key="request.id"
          class="request-item"
        >
          <view class="user-avatar-section">
            <image 
              v-if="request.toUser.avatar" 
              :src="request.toUser.avatar" 
              class="user-avatar"
              mode="aspectFill"
            />
            <view v-else class="default-avatar">
              <text class="avatar-text">{{ request.toUser.name.charAt(0) }}</text>
            </view>
          </view>
          
          <view class="request-info">
            <text class="user-name">{{ request.toUser.name }}</text>
            <text class="request-message">{{ request.message || '我想加你为好友' }}</text>
            <text class="request-time">{{ formatTime(request.createTime) }}</text>
          </view>
          
          <view class="request-status">
            <text :class="['status-text', request.status]">
              {{ getStatusText(request.status) }}
            </text>
            <button 
              v-if="request.status === 'pending'"
              class="cancel-btn" 
              @click="cancelRequest(request)"
            >
              撤回
            </button>
          </view>
        </view>
      </view>
    </view>
    
    <!-- 系统通知 -->
    <view v-if="activeCategory === 'notifications'" class="notifications-list">
      <view class="section-title">
        <text class="title-text">系统通知</text>
      </view>
      
      <view v-if="notifications.length === 0" class="empty-state">
        <text class="empty-icon">🔔</text>
        <text class="empty-text">暂无系统通知</text>
      </view>
      
      <view v-else class="notification-list">
        <view 
          v-for="notification in notifications" 
          :key="notification.id"
          class="notification-item"
          :class="{ unread: !notification.read }"
        >
          <view class="notification-icon">
            <text class="icon-text">{{ notification.icon }}</text>
          </view>
          
          <view class="notification-content">
            <text class="notification-title">{{ notification.title }}</text>
            <text class="notification-text">{{ notification.content }}</text>
            <text class="notification-time">{{ formatTime(notification.time) }}</text>
          </view>
          
          <view v-if="!notification.read" class="unread-dot"></view>
        </view>
      </view>
    </view>
    
    <!-- 批量操作 -->
    <view v-if="receivedRequests.length > 0 && activeCategory === 'received'" class="batch-actions">
      <button class="batch-btn" @click="acceptAllRequests">
        全部同意
      </button>
      <button class="batch-btn reject" @click="rejectAllRequests">
        全部拒绝
      </button>
    </view>
  </view>
</template>

<script>
import apiService from '@/utils/api-service.js'
import appStateManager from '@/utils/app-state-manager.js'

export default {
  data() {
    return {
      activeCategory: 'received',
      categories: [
        { id: 'received', name: '收到的', count: 0 },
        { id: 'sent', name: '已发送', count: 0 },
        { id: 'notifications', name: '通知', count: 0 }
      ],
      receivedRequests: [],
      sentRequests: [],
      notifications: [],
      isServerOnline: false,
      serverStateUnsubscribe: null  // 🔧 保存取消订阅函数
    }
  },
  
  computed: {
    pendingCount() {
      return this.receivedRequests.filter(req => req.status === 'pending').length
    },
    
    receivedCount() {
      return this.receivedRequests.length
    },
    
    sentCount() {
      return this.sentRequests.length
    }
  },
  
  onLoad() {
    // 订阅服务器状态
    this.serverStateUnsubscribe = appStateManager.subscribe('server', (serverState) => {
      this.isServerOnline = serverState.isOnline
      if (serverState.isOnline) {
        this.loadRequestsData()  // ✅ 修正方法名
      }
    })
    
    // 初始加载数据
    this.loadRequestsData()
  },
  
  onUnload() {
    // 🔧 关键修复：取消订阅，防止在其他页面执行回调
    if (this.serverStateUnsubscribe) {
      this.serverStateUnsubscribe()
      this.serverStateUnsubscribe = null
    }
  },
  
  methods: {
    // 检查服务器状态

    
    async loadRequestsData() {
      try {
        // 获取当前用户信息
        const currentUser = uni.getStorageSync('currentUser')
        if (!currentUser) {
          uni.showModal({
            title: '未登录',
            content: '请先登录后再使用好友功能',
            showCancel: false,
            confirmText: '确定',
            success: () => {
              uni.navigateBack()
            }
          })
          return
        }

        const userData = JSON.parse(currentUser)
        
        // 检查用户ID是否存在
        if (!userData.id) {
          uni.showModal({
            title: '用户信息不完整',
            content: '用户信息缺少ID，请重新登录',
            showCancel: false,
            confirmText: '确定',
            success: () => {
              uni.navigateBack()
            }
          })
          return
        }
        
        console.log('从服务器获取好友请求数据...')
        
        // 获取收到的请求
        const receivedResponse = await apiService.getFriendRequests(userData.id, 'received')
        if (receivedResponse.code === 'SUCCESS') {
          if (receivedResponse.data && receivedResponse.data.length > 0) {
            this.receivedRequests = receivedResponse.data.map(req => ({
              id: req.id,
              fromUser: {
                id: req.from_user.id,
                name: req.from_user.name || '未知用户',
                email: req.from_user.email || '',
                avatar: req.from_user.avatar || ''
              },
              message: req.message,
              status: req.status,
              createdAt: req.created_at
            }))
          } else {
            // 服务器返回空数据，清空收到的请求
            this.receivedRequests = []
          }
        } else {
          // 服务器请求失败，清空收到的请求
          this.receivedRequests = []
        }
        
        // 获取发送的请求
        const sentResponse = await apiService.getFriendRequests(userData.id, 'sent')
        if (sentResponse.code === 'SUCCESS') {
          if (sentResponse.data && sentResponse.data.length > 0) {
            this.sentRequests = sentResponse.data.map(req => ({
              id: req.id,
              toUser: {
                id: req.to_user.id,
                name: req.to_user.name || '未知用户',
                email: req.to_user.email || '',
                avatar: req.to_user.avatar || ''
              },
              message: req.message,
              status: req.status,
              createdAt: req.created_at
            }))
          } else {
            // 服务器返回空数据，清空发送的请求
            this.sentRequests = []
          }
        } else {
          // 服务器请求失败，清空发送的请求
          this.sentRequests = []
        }
        
        console.log('成功加载好友请求数据:', this.receivedRequests.length, '个收到请求,', this.sentRequests.length, '个发送请求')
        
        // 更新分类计数
        this.categories[0].count = this.receivedRequests.length
        this.categories[1].count = this.sentRequests.length
        this.categories[2].count = this.notifications.filter(n => !n.read).length
        
      } catch (error) {
        console.error('加载请求数据失败:', error)
        this.receivedRequests = []
        this.sentRequests = []
        uni.showToast({
          title: '加载好友请求失败',
          icon: 'error'
        })
      }
    },

    
    switchCategory(categoryId) {
      this.activeCategory = categoryId
    },
    
    async acceptRequest(request) {
      try {
        // 获取当前用户信息
        const currentUser = uni.getStorageSync('currentUser')
        if (!currentUser) {
          uni.showToast({
            title: '用户未登录',
            icon: 'error'
          })
          return
        }

        const userData = JSON.parse(currentUser)
        
        // 检查请求ID是否有效
        if (!request.id) {
          console.error('请求ID无效:', request)
          uni.showToast({
            title: '请求ID无效',
            icon: 'error'
          })
          return
        }
        
        // 尝试从服务器处理好友请求
        const serverStatus = appStateManager.getState("server")
        if (serverStatus.isOnline) {
          try {
            console.log('发送同意请求到服务器:', {
              requestId: request.id,
              userId: userData.id,
              action: 'accept'
            })
            
            const response = await apiService.respondToFriendRequest(request.id, userData.id, 'accept')
            if (response.code === 'SUCCESS') {
              console.log('服务器处理好友请求成功')
              
              // 服务器处理成功，重新加载数据
              await this.loadRequestsData()
              
              uni.showToast({
                title: '已同意好友请求',
                icon: 'success'
              })
              return
            } else {
              console.error('服务器处理失败:', response)
              uni.showToast({
                title: '服务器处理失败',
                icon: 'error'
              })
              return
            }
          } catch (error) {
            console.error('服务器处理好友请求失败:', error)
            uni.showToast({
              title: '网络错误，请重试',
              icon: 'error'
            })
            return
          }
        } else {
          uni.showToast({
            title: '服务器离线，无法处理请求',
            icon: 'error'
          })
          return
        }
        
      } catch (error) {
        uni.showToast({
          title: '操作失败',
          icon: 'error'
        })
      }
    },
    
    async rejectRequest(request) {
      try {
        // 获取当前用户信息
        const currentUser = uni.getStorageSync('currentUser')
        if (!currentUser) {
          uni.showToast({
            title: '用户未登录',
            icon: 'error'
          })
          return
        }

        const userData = JSON.parse(currentUser)
        
        // 检查请求ID是否有效
        if (!request.id) {
          console.error('请求ID无效:', request)
          uni.showToast({
            title: '请求ID无效',
            icon: 'error'
          })
          return
        }
        
        // 尝试从服务器处理好友请求
        const serverStatus = appStateManager.getState("server")
        if (serverStatus.isOnline) {
          try {
            console.log('发送拒绝请求到服务器:', {
              requestId: request.id,
              userId: userData.id,
              action: 'reject'
            })
            
            const response = await apiService.respondToFriendRequest(request.id, userData.id, 'reject')
            if (response.code === 'SUCCESS') {
              console.log('服务器处理好友请求成功')
              
              // 服务器处理成功，重新加载数据
              await this.loadRequestsData()
              
              uni.showToast({
                title: '已拒绝好友请求',
                icon: 'success'
              })
              return
            } else {
              console.error('服务器处理失败:', response)
              uni.showToast({
                title: '服务器处理失败',
                icon: 'error'
              })
              return
            }
          } catch (error) {
            console.error('服务器处理好友请求失败:', error)
            uni.showToast({
              title: '网络错误，请重试',
              icon: 'error'
            })
            return
          }
        } else {
          uni.showToast({
            title: '服务器离线，无法处理请求',
            icon: 'error'
          })
          return
        }
        
      } catch (error) {
        uni.showToast({
          title: '操作失败',
          icon: 'error'
        })
      }
    },
    
    async cancelRequest(request) {
      try {
        uni.showModal({
          title: '撤回请求',
          content: '确定要撤回这个好友请求吗？',
          success: (res) => {
            if (res.confirm) {
              // 移除请求
              this.sentRequests = this.sentRequests.filter(req => req.id !== request.id)
              this.categories[1].count = this.sentRequests.length
              this.saveRequestsData()
              
              uni.showToast({
                title: '已撤回请求',
                icon: 'success'
              })
            }
          }
        })
      } catch (error) {
        uni.showToast({
          title: '操作失败',
          icon: 'error'
        })
      }
    },
    
    acceptAllRequests() {
      uni.showModal({
        title: '批量同意',
        content: `确定要同意所有${this.receivedRequests.length}个好友请求吗？`,
        success: (res) => {
          if (res.confirm) {
            this.receivedRequests.forEach(request => {
              this.acceptRequest(request)
            })
          }
        }
      })
    },
    
    rejectAllRequests() {
      uni.showModal({
        title: '批量拒绝',
        content: `确定要拒绝所有${this.receivedRequests.length}个好友请求吗？`,
        success: (res) => {
          if (res.confirm) {
            this.receivedRequests.forEach(request => {
              this.rejectRequest(request)
            })
          }
        }
      })
    },
    
    addToFriendsList(friend) {
      try {
        const friendsData = uni.getStorageSync('friends_list') || '[]'
        const friendsList = JSON.parse(friendsData)
        
        // 检查是否已存在
        const existingIndex = friendsList.findIndex(f => f.id === friend.id)
        if (existingIndex === -1) {
          friendsList.push(friend)
          uni.setStorageSync('friends_list', JSON.stringify(friendsList))
        }
      } catch (error) {
        console.error('添加到好友列表失败:', error)
      }
    },
    
    saveRequestsData() {
      try {
        // 获取当前用户信息
        const currentUser = uni.getStorageSync('currentUser')
        if (!currentUser) {
          console.log('用户未登录，无法保存数据')
          return
        }

        const userData = JSON.parse(currentUser)
        
        // 按用户ID保存数据
        const userRequests = {
          received: this.receivedRequests,
          sent: this.sentRequests
        }
        uni.setStorageSync(`friend_requests_${userData.id}`, JSON.stringify(userRequests))
      } catch (error) {
        console.error('保存请求数据失败:', error)
      }
    },
    
    getStatusText(status) {
      const statusMap = {
        'pending': '待处理',
        'accepted': '已同意',
        'rejected': '已拒绝'
      }
      return statusMap[status] || '未知'
    },
    
    formatTime(time) {
      const now = new Date()
      const targetTime = new Date(time)
      const diff = now - targetTime
      
      if (diff < 60000) { // 1分钟内
        return '刚刚'
      } else if (diff < 3600000) { // 1小时内
        return `${Math.floor(diff / 60000)}分钟前`
      } else if (diff < 86400000) { // 1天内
        return `${Math.floor(diff / 3600000)}小时前`
      } else {
        return targetTime.toLocaleDateString()
      }
    }
  }
}
</script>

<style scoped>
.requests-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  padding: 20rpx;
}

/* 统计信息 */
.stats-section {
  display: flex;
  background: white;
  border-radius: 16rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
}

.stat-item {
  flex: 1;
  text-align: center;
}

.stat-number {
  display: block;
  font-size: 36rpx;
  font-weight: bold;
  color: #667eea;
  margin-bottom: 8rpx;
}

.stat-label {
  display: block;
  font-size: 22rpx;
  color: #666;
}

/* 分类标签 */
.category-tabs {
  display: flex;
  background: white;
  border-radius: 16rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.category-tab {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 24rpx;
  position: relative;
  transition: all 0.3s ease;
}

.category-tab.active {
  background: #667eea;
  color: white;
}

.tab-text {
  font-size: 26rpx;
  font-weight: 500;
}

.tab-badge {
  position: absolute;
  top: 8rpx;
  right: 8rpx;
  background: #ff4757;
  color: white;
  font-size: 18rpx;
  padding: 2rpx 6rpx;
  border-radius: 8rpx;
  min-width: 20rpx;
  text-align: center;
}

.category-tab.active .tab-badge {
  background: rgba(255, 255, 255, 0.3);
}

/* 请求列表 */
.requests-list {
  background: white;
  border-radius: 16rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
}

.section-title {
  display: flex;
  align-items: center;
  margin-bottom: 30rpx;
}

.title-text {
  font-size: 28rpx;
  font-weight: bold;
  color: #333;
}

.title-count {
  font-size: 22rpx;
  color: #999;
  margin-left: 8rpx;
}

.empty-state {
  text-align: center;
  padding: 60rpx 20rpx;
}

.empty-icon {
  display: block;
  font-size: 80rpx;
  margin-bottom: 20rpx;
}

.empty-text {
  font-size: 26rpx;
  color: #999;
}

.request-list, .notification-list {
  display: flex;
  flex-direction: column;
  gap: 20rpx;
}

.request-item, .notification-item {
  display: flex;
  align-items: center;
  padding: 20rpx;
  background: #f8f9fa;
  border-radius: 12rpx;
  position: relative;
}

.notification-item.unread {
  background: #e3f2fd;
  border-left: 4rpx solid #2196f3;
}

.user-avatar-section {
  margin-right: 20rpx;
}

.user-avatar {
  width: 80rpx;
  height: 80rpx;
  border-radius: 50%;
}

.default-avatar {
  width: 80rpx;
  height: 80rpx;
  border-radius: 50%;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  align-items: center;
  justify-content: center;
}

.avatar-text {
  color: white;
  font-size: 32rpx;
  font-weight: bold;
}

.request-info, .notification-content {
  flex: 1;
}

.user-name {
  display: block;
  font-size: 28rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 4rpx;
}

.request-message, .notification-text {
  display: block;
  font-size: 24rpx;
  color: #666;
  margin-bottom: 4rpx;
}

.request-time, .notification-time {
  display: block;
  font-size: 20rpx;
  color: #999;
}

.request-actions {
  display: flex;
  gap: 12rpx;
}

.accept-btn {
  background: #27ae60;
  color: white;
  border: none;
  border-radius: 20rpx;
  padding: 12rpx 20rpx;
  font-size: 22rpx;
}

.reject-btn {
  background: #e74c3c;
  color: white;
  border: none;
  border-radius: 20rpx;
  padding: 12rpx 20rpx;
  font-size: 22rpx;
}

.request-status {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  gap: 8rpx;
}

.status-text {
  font-size: 22rpx;
  padding: 4rpx 12rpx;
  border-radius: 12rpx;
}

.status-text.pending {
  background: #f39c12;
  color: white;
}

.status-text.accepted {
  background: #27ae60;
  color: white;
}

.status-text.rejected {
  background: #e74c3c;
  color: white;
}

.cancel-btn {
  background: #95a5a6;
  color: white;
  border: none;
  border-radius: 16rpx;
  padding: 8rpx 16rpx;
  font-size: 20rpx;
}

/* 通知相关 */
.notification-icon {
  margin-right: 20rpx;
}

.icon-text {
  font-size: 40rpx;
}

.notification-title {
  display: block;
  font-size: 26rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 4rpx;
}

.unread-dot {
  position: absolute;
  top: 16rpx;
  right: 16rpx;
  width: 16rpx;
  height: 16rpx;
  background: #ff4757;
  border-radius: 50%;
}

/* 批量操作 */
.batch-actions {
  display: flex;
  gap: 20rpx;
  margin-bottom: 20rpx;
}

.batch-btn {
  flex: 1;
  background: #667eea;
  color: white;
  border: none;
  border-radius: 16rpx;
  padding: 24rpx;
  font-size: 26rpx;
  font-weight: 500;
}

.batch-btn.reject {
  background: #e74c3c;
}
</style>
